import React, { Component } from "react";
import PubSub from "pubsub-js";
// import axios from "axios";

export default class Search extends Component {
  search = async () => {
    //获取用户的输入
    const {
      keyWordElement: { value: keyWord },
    } = this;
    // console.log(keyWord);
    // https://api.github.com/search/users?q=${keyWord}
    // this.props.updateAppState({ isFirst: false, isLoading: true });
    PubSub.publish("tk", { isFirst: false, isLoading: true });

    //#region 发送网络请求-axios
    // axios.get(`/api/search/users2?q=${keyWord}`).then(
    //   (response) => {
    //     PubSub.publish("tk", { isLoading: false, users: response.data.items });
    //     // this.props.updateAppState({
    //     //   isLoading: false,
    //     //   users: response.data.items,
    //     // });
    //   },
    //   (error) => {
    //     PubSub.publish("tk", { isLoading: false, err: error.message });
    //     // this.props.updateAppState({
    //     //   isLoading: false,
    //     //   err: error.message,
    //     // });
    //   }
    // );
    //#endregion

    //发送网络请求-fetch(未优化)
    /* fetch(`/api/search/users2?q=${keyWord}`).then(
      (response) => {
        console.log("联系服务器成功了");
        return response.json();
      },
      (error) => {
        console.log("联系服务器失败了", error);
        return new Promise(()=>{})
      }
    ).then(
      response => {console.log('请求数据成功了',response);},
      error => {console.log('请求数据失败了',error);}
    ); */

    //发送网络请求-fetch(优化)
    /* fetch(`/api/search/users2?q=${keyWord}`).then(
      (response) => {
        console.log("联系服务器成功了");
        return response.json();
      },
    
    ).then(
      response => {console.log('请求数据成功了',response);},
    ).catch(
      (error)=>{console.log(error);}
    ); */

    // async
    try {
      const response = await fetch(`/api/search/users2?q=${keyWord}`);
      const data = await response.json();
      PubSub.publish("tk", { isLoading: false, users: data.items });
    } catch (error) {
      console.log(error);
      PubSub.publish("tk", { isLoading: false, err: error.message });
    }
  };

  render() {
    return (
      <div>
        <section className="jumbotron">
          <h3 className="jumbotron-heading">搜索Github用户</h3>
          <div>
            <input
              ref={(c) => (this.keyWordElement = c)}
              type="text"
              placeholder="输入关键词点击搜索"
            />
            &nbsp;<button onClick={this.search}>搜索</button>
          </div>
        </section>
      </div>
    );
  }
}
